import {
  ENERGY_CONSUMPTION_STRUCTURE_TABLE,
  ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE,
  TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT,
  ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
  PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE,
  ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE,
  REPORT_REPORT,

  ENTERPRISE_BASIC_INFORMATION_TABLE_NAME,
  TABLE_ACCOUNT_CONFIGS,
  // TABLE_REPORTED,
  // TABLE_RESOLVED,

  T_NOT_FILLED,
  T_FILLING,
  T_FILLED,
  T_REPORTED,
  T_REJECT,
  T_RESOLVED,
  T_REJECT_FILLING,
  T_REJECT_FILLED,
  T_REJECT_REPORTED,

  TABLE_FIELD_YEAR,
  TABLE_FIELD_QUARTER,
} from '@/config'

/* IFTRUE_ONLY_NANCHANG
import { loadReportingSituation, getFiveYearPlanInfo } from '@/api/enterpriseQuarterlyReport2'
FITRUE_ONLY_NANCHANG */
/* IFTRUE_NOT_NANCHANG */
import { loadReportingSituation, getFiveYearPlanInfo } from '@/api/enterpriseQuarterlyReport'
/* FITRUE_NOT_NANCHANG */

async function getData (params) {
  const isYear = params.quarter === 5;
  const prefix = isYear ? '工业年' : '工业季';
  const option = {
    [TABLE_FIELD_YEAR]: params.year,
    [TABLE_FIELD_QUARTER]: params.quarter,
  }
  return loadReportingSituation(option).then(res => {
    res.data = res.data || []

    const ids = isYear
    ? [
     ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
     ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID,
     ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID,
     TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID,
     PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID,
     ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID
    ]
    : [
     ENERGY_CONSUMPTION_STRUCTURE_TABLE.ID,
     ENERGY_CONSUMPTION_STRUCTURE_SUB_TABLE.ID,
     TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID,
    ]


    const data = ids.reduce((acc, vv) => {
      const target = res.data.find(v => +v.id === vv);
      target && acc.push(target);
      return acc
    }, [])
    return data.map(v => ({
      tableId: +v.id,
      name: prefix + REPORT_REPORT[v.id].name,
      alias: prefix + REPORT_REPORT[v.id].alias,
      status: v.state,
      statusText: v.stateName,
      remark: v.illustrate
    }))
  })
}

let is_click_on_drag_ball = true;

export default {
  data () {
    return {
      loading: false,
      lists: [],

      // 五年计划表头字段
      fiveYearsColumns: {
        column1: '',
        column2: '',
        column3: '',
        column4: '',
        column5: '',
      },

      // 表1-4
      small_numeral_name: '',
      first_of_five_year_plan: '',
    }
  },
  computed: {
    userInfo () {
      return this.$store.state.user.userInfo || {}
    },
    enterpriseId () {
      const { tenantId } = this.userInfo
      return tenantId ? String(tenantId) : null
    },
    enterpriseName () {
      const { tenantName, userName } = this.userInfo
      return tenantName || userName || ''
    },
    showFixAppendEmptyRowBall () {
      // 表1-1，1-3，1-5 需要显示追加空行
      return [
        ENTERPRISE_BASIC_INFORMATION_TABLE_ID,
        TABLE_OF_COMPREHENSIVE_ENERGY_CONSUMPTION_PER_UNIT_PRODUCT.ID,
        ENERGY_SAVING_RENOVATION_PROJECT_INFORMATION_TABLE.ID
      ].includes(this.tableAccountId) && !this.readonly
    }
  },
  methods: {
    async getLists (params) {
      this.loading = true
      try {
        const data = await getData(params)
        this.lists = data || []
      } finally {
        this.loading = false
      }
    },
    getTableName (tableAccountId) {
      // 企业基本情况表
      if (Number(tableAccountId) === ENTERPRISE_BASIC_INFORMATION_TABLE_ID) {
        return ENTERPRISE_BASIC_INFORMATION_TABLE_NAME
      }
      let value, target
      for (const key in TABLE_ACCOUNT_CONFIGS) {
        value = TABLE_ACCOUNT_CONFIGS[key]
        if (value.ID === Number(tableAccountId)) {
          target = value
        }
      }
      if (target) {
        return target.NAME
      }
      return ''
    },
    findTable (id) {
      const tables = Object.keys(TABLE_ACCOUNT_CONFIGS)
      const key = tables.find(key => TABLE_ACCOUNT_CONFIGS[key].ID === Number(id))
      return key ? TABLE_ACCOUNT_CONFIGS[key] : null
    },
    async edit (row, readonly = false) {
      const tableAccountId = row.tableId

      if (tableAccountId == null) return false

      this.tableStatus = row.status
      // 企业报表已上报或已审核或退回已上报
      this.readonly = readonly || row.status === T_REPORTED ||
      row.status === T_RESOLVED ||
      row.status === T_REJECT_REPORTED

      // 企业基础情况表
      if (tableAccountId === ENTERPRISE_BASIC_INFORMATION_TABLE_ID) {
        this.tableAccountId = ENTERPRISE_BASIC_INFORMATION_TABLE_ID
        this.tableName = ENTERPRISE_BASIC_INFORMATION_TABLE_NAME
        this.tableColumns = []

        this.$nextTick(() => {
          this.showTableAccount = true
        })
        return
      }

      const TABLE_ACCOUNT = this.findTable(tableAccountId)
      if (TABLE_ACCOUNT === null) {
        return false
      }
      this.tableAccountId = Number(tableAccountId)
      this.tableName = TABLE_ACCOUNT.NAME
      this.tableColumns = TABLE_ACCOUNT.COLUMNS

      // 进度节能目标完成情况表 动态的"五年"
      if (tableAccountId === PROGRESS_ENERGY_SAVING_TARGET_COMPLETION_TABLE.ID) {
        const five = await getFiveYearPlanInfo(this.year)
          .then(({ data }) => {
            data = data || {}
            const yearList = data.yearList || []
            if (yearList.length > 0) {
              this.small_numeral_name = data.smallNumeralName;
              this.first_of_five_year_plan = yearList[0]

              const a = (y) => `${y}年`;

              this.fiveYearsColumns.column1 = a(yearList[0]);
              this.fiveYearsColumns.column2 = a(yearList[1]);
              this.fiveYearsColumns.column3 = a(yearList[2]);
              this.fiveYearsColumns.column4 = a(yearList[3]);
              this.fiveYearsColumns.column5 = a(yearList[4]);
              return {
                oneYear: a(yearList[0]),
                twoYear: a(yearList[1]),
                threeYear: a(yearList[2]),
                fourYear: a(yearList[3]),
                fiveYear: a(yearList[4]),
              }
            }
            return {
              oneYear: 'xx年',
              twoYear: 'xx年',
              threeYear: 'xx年',
              fourYear: 'xx年',
              fiveYear: 'xx年',
            }
          })

        const cols = [...this.tableColumns]
        Object.keys(five).forEach(key => {
          const target = cols.find(col => col.prop === key)
          if (target) {
            target.label = five[key]
          }
        })

        this.tableColumns = cols
      }

      this.$nextTick(() => {
        this.showTableAccount = true
      })
    },
    statusTagType (state) {
      switch (state) {
        case T_NOT_FILLED:
          return 'warning'
        case T_RESOLVED:
          return 'success'
        case T_REJECT:
          return 'danger'
        default:
          return 'info'
      }
    },
    getVisible (state, button) {
      // 填写
      if (button === 1) {
        return state === T_NOT_FILLED
      }
      // 修改
      if (button === 2) {
        return [
          T_FILLING,
          T_FILLED,
          T_REJECT,
          T_REJECT_FILLING,
          T_REJECT_FILLED,
        ].includes(state)
      }
      // 查看、历史
      if (button === 3 || button === 4) {
        return state !== T_NOT_FILLED
      }
    },
    // 保存（保存为已填写或退回已填写)
    saveFilled () {
      // eslint-disable-next-line
      const status = this.tableStatus;
      // this.report(T_REPORTED);
      if (Number(status) <= Number(T_FILLED)) {
        this.report(T_FILLED);
      } else {
        this.report(T_REJECT_FILLED);
      }
    },

    dragMovingHandler () {
      is_click_on_drag_ball = false;
    },
    clickFixAppendEmptyRowBall (evt) {
      if (!is_click_on_drag_ball) {
        is_click_on_drag_ball = true;
        return;
      }
      if (evt && evt.preventDefault) {
        evt.preventDefault();
        evt.stopPropagation();
      }
      // 追加空行
      if (this.$refs.quarterlyAccountTable && this.$refs.quarterlyAccountTable.appendRow) {
        this.$refs.quarterlyAccountTable.appendRow()
      }
    },
  },
}
